package com.gxg.newdemo1.mynewdamo1.ca;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.gxg.newdemo1.mynewdamo1.R;
import com.gxg.newdemo1.mynewdamo1.channel.util.GsonUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.socks.library.KLog;

import org.json.JSONObject;

import cn.org.bjca.signet.helper.bean.OCRInfoBean;
import cn.org.bjca.signet.helper.bean.SignDataInfos;
import cn.org.bjca.signet.helper.utils.StringUtils;
import cn.org.bjca.signet.sdk.MessageControler;
import cn.org.bjca.signet.sdk.OfflineSignResultEntity;
import cn.org.bjca.signet.sdk.ResultEntity;
import cn.org.bjca.signet.sdk.SignetCallBack;
import cn.org.bjca.signet.sdk.SignetSDKInstance;
import cn.org.bjca.signet.sdk.UserEntity;

public class TestActivity extends Activity implements SignetCallBack {

	private SignetSDKInstance sdkInstance; // SDK实例
//	private String appId = "67f6c99b74484c2b8bcb35473850cdd7";

	private String appId = "APP_50D36379147E489E99D15E22976FF71F";
	private String msspID = "e6333fcd892948ea61954d3107eb8e8d9b21f4d419f0cdf3805b4226a65bd974";
	private String enMsspId = "ENA_a68e7f48-dc40-4d04-a602-55426873d6e3";

	private Button btnRegister, btnAnonymousReg, btnSelfReg, btnQrReg;

	private Button btnLogin, btnQrLogin, btnSignData, btnQrSignData, btnAddSignId, btnSignDocu;

	private Button btnSetHandWrite, btnPicHandWrite;

	private Button btnFindBackUser, btnFindBackUserBy, btnFindBackEnter, btnFindBackEnterBy;

	private Button btnNextPage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);

		sdkInstance = SignetSDKInstance.getInstance(appId);
		findView();
	}

	private void findView() {

		// 个人用户注册
		btnRegister = (Button) findViewById(R.id._test_register);
		btnRegister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				//激活码，由业务后台通过网关向云服务后台推送可信用户信息获取，支持个人用户/企业用户，将云服务后台返回的激活JSON串做参数传入register接口即可
				//激活码一次有效
				String activeCode = "{\"version\":\"2.0\",\"operType\":\"ActiveUser\",\"data\":\"8e17f9b8\"}";

				sdkInstance.register(TestActivity.this, activeCode);

			}
		});

		// 匿名用户注册
		btnAnonymousReg = (Button) findViewById(R.id._test_anonymous_reg);
		btnAnonymousReg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.anonymousRegister(TestActivity.this, null, "df2be865", "15313195026001");
			}
		});

		// 自注册，需要后台配置开通自注册策略方可调用该接口
		btnSelfReg = (Button) findViewById(R.id._test_self_register);
		btnSelfReg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.selfRegister(TestActivity.this);
			}
		});

		// 二维码注册
		btnQrReg = (Button) findViewById(R.id._test_qr_reg);
		btnQrReg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.qrRegister(TestActivity.this);

			}
		});

		// 登录，signJobId由业务后台通过网关向云服务后台推送一次登录请求获取
		btnLogin = (Button) findViewById(R.id._test_login);
		btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String signJobId = "SDG_84fdedf8-d636-4dc4-8ece-a14d6e18f67b";	//获取的signJobId有效期为三天
				
				sdkInstance.login(TestActivity.this, msspID, signJobId);

			}
		});

		// 二维码登录
		btnQrLogin = (Button) findViewById(R.id._test_qr_login);
		btnQrLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.qrLogin(TestActivity.this, msspID);

			}
		});

		// 数据签名，由业务后台向云服务后台推送一次签名请求获取
		btnSignData = (Button) findViewById(R.id._test_sign_data);
		btnSignData.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String signJobId = "SDG_c8cfdcfa-ded0-444a-a06b-23f3983a3cd0";		//获取的signJobId有效期为三天
				sdkInstance.signData(TestActivity.this, msspID, signJobId);

			}
		});

		// 二维码签名
		btnQrSignData = (Button) findViewById(R.id._test_qr_sign_data);
		btnQrSignData.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.qrSignData(TestActivity.this, msspID);

			}
		});

		// 客户端发起签名任务
		btnAddSignId = (Button) findViewById(R.id._test_add_sign_data_job);
		btnAddSignId.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				List<SignDataInfos> signDataInfos = new ArrayList<SignDataInfos>();
				String text = "text1;test2;test3";
				String[] signDatas = text.split(";");

				for (int i = 0; i < signDatas.length; i++) {
					SignDataInfos signDataInfo = new SignDataInfos();
					signDataInfo.setBusinessId(String.valueOf(i + 1));
					signDataInfo.setData(StringUtils.base64Encode(signDatas[i].getBytes()));
					signDataInfo.setSerialNum(String.valueOf(i + 1));
					signDataInfos.add(signDataInfo);
				}
				sdkInstance.addsigndatajob(TestActivity.this, msspID, "SHA1withRSA", "CLEAR_DATA", "SIGN",
						"测试addsigndatajob", signDataInfos);

			}
		});

		// 文档签署，由业务后台通过网关向云服务后台推送一篇待签文档获取
		btnSignDocu = (Button) findViewById(R.id._test_sign_docu);
		btnSignDocu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String docuId = "DOCU_ee5134ca-a9c5-4fc2-9c85-7b7b5fa261f5";

				sdkInstance.signDocu(TestActivity.this, msspID, docuId);
			}
		});

		// 手写签名
		btnSetHandWrite = (Button) findViewById(R.id._test_set_hand_writing);
		btnSetHandWrite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.setHandWriting(TestActivity.this, msspID);

			}
		});

		// 拍照签名
		btnPicHandWrite = (Button) findViewById(R.id._test_pic_hand_writing);
		btnPicHandWrite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.pictureHandWriting(TestActivity.this, msspID);

			}
		});

		// 个人用户传参找回，该测试用户短信验证码为123456
		btnFindBackUser = (Button) findViewById(R.id._test_find_back_user);
		btnFindBackUser.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				sdkInstance.findBackUser(TestActivity.this, "高续铬", "141124199004090058");
				
			}
		});

		// 个人用户信步云找回；测试数据：
		//姓名：王刚，身份证号码：110116198107268807，短信验证码123456
		btnFindBackUserBy = (Button) findViewById(R.id._test_find_back_user_bysignet);
		btnFindBackUserBy.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.findbackUserBySignet(TestActivity.this);

			}
		});

		// 企业用户传参找回，该测试用户短信验证码为123456
		btnFindBackEnter = (Button) findViewById(R.id._test_find_back_enter);
		btnFindBackEnter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sdkInstance.findbackEnterprise(TestActivity.this, "云签名测试法人", "320683199206109730", "000111222333");
			}
		});

		// 企业用户信步云找回，测试数据：
		//组织机构代码：000111222333；法人姓名：云签名测试法人；法人身份证号码：320683199206109730
		btnFindBackEnterBy = (Button) findViewById(R.id._test_find_back_enter_bysignet);
		btnFindBackEnterBy.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				sdkInstance.findbackEnterpriseBySignet(TestActivity.this);

			}
		});

		// 下一页
		btnNextPage = (Button) findViewById(R.id._test_next_page);
		btnNextPage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(TestActivity.this, TestTwoActivity.class);
				startActivity(intent);

			}
		});


		findViewById(R.id.login).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				HashMap<String, String> userList = sdkInstance.getUserList(TestActivity.this);
				Set<String> strings = userList.keySet();

				for (String string : strings) {
					msspID = string;
					String userName = userList.get(string);
					KLog.e("sss   "+msspID);
					KLog.e("sss  "+userName);
				}
                String url = "http://192.168.199.165/wenShuController/beginPinCodeLogin.action";
                OkGo.<String>get(url)
                        .tag(TestActivity.this.getClass().getSimpleName())
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                String signJobId = "";
                                try {
                                    JSONObject jsonObject = new JSONObject(response.body());
                                    boolean errcode = jsonObject.getBoolean("rtState");
                                    String message = jsonObject.getString("rtMsg");
                                    if (errcode) {
                                        signJobId = jsonObject.getString("rtData");
                                        KLog.e("sss  "+signJobId);
										sdkInstance.login(TestActivity.this, msspID, signJobId);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
			}
		});

	}

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (sdkInstance != null) {
                MessageControler.messageHandle(TestActivity.this, data);
            }
        }

        @Override
        public void loginCallBack(ResultEntity result) {
            KLog.e("sss  "+result.getStatus());
            KLog.e("sss  "+result.getCert());
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                Map<String,String> map = new HashMap<>();
                map.put("scret",result.getCert());
                String url = "http://192.168.199.165/wenShuController/checkPinCodeLogin.action";
                OkGo.<String>post(url)
                        .tag(TestActivity.this.getClass().getSimpleName())
                        .params(map)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                String signJobId = "";
                                try {
                                    JSONObject jsonObject = new JSONObject(response.body());
                                    boolean errcode = jsonObject.getBoolean("rtState");
                                    String message = jsonObject.getString("rtMsg");
                                    if (errcode) {
    //									signJobId = jsonObject.getString("rtData");
    //									KLog.e("sss  "+signJobId);
    //									sdkInstance.login(TestActivity.this, msspID, signJobId);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
            } else {
                Toast.makeText(TestActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void qrLoginCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "二维码登录成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "二维码登录失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void registerCallBack(ResultEntity result) {

            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "激活成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "激活失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void qrRegisterCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "二维码注册成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "二维码注册失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void signDataCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "数据签名成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "数据签名失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void qrSignDataCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "二维码签名成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "二维码签名失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void findBackUserCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "找回成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "找回失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void signDocuCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "文档签署成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "文档签署失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void setHandWritingCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "签名笔迹设置成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "签名笔迹设置失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void selfRegisterCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "自注册成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "自注册失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void setFingerCallBack(ResultEntity result) {
            // TODO Auto-generated method stub

        }

        @Override
        public void selfRegInfoCallBack(UserEntity result) {
            // TODO Auto-generated method stub

        }

        @Override
        public void selfRegGetOcrCallBack(OCRInfoBean result) {
            // TODO Auto-generated method stub

        }

        @Override
        public void enterPriseSealCallBack(ResultEntity result) {
            // TODO Auto-generated method stub

        }

        @Override
        public void reqOfflineCertCallBack(ResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "申请离线证书成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "申请离线证书失败", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void offlineSignCallBack(OfflineSignResultEntity result) {
            if (result.getStatus().equalsIgnoreCase("0000")) {
                Toast.makeText(TestActivity.this, "申请离线证书成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestActivity.this, "申请离线证书失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void enterPriseSealSingleCallBack(ResultEntity result) {
            // TODO Auto-generated method stub

        }

        @Override
        public void enterPriseSealImageSingleCallBack(ResultEntity result) {
            // TODO Auto-generated method stub

        }

        @Override
        public void getDocuInfoCallBack(ResultEntity result) {
            // TODO Auto-generated method stub

        }
}
